import BaseMapper from '../../db/mapper/BaseMapper'
import db from '../../db'
import TABLES from '../../db/util/table'
import { generateUUID } from '../../util'
import userStore from '../../store/user'
import session from '../session'
import Lock from '../../util/lock'


class MessageService {

  sessionListMapper = new BaseMapper(db , TABLES.SESSION_LIST.TABLE_NAME , TABLES.SESSION_LIST.TABLE_ID_COLUMN);

  chatListMapper = new BaseMapper(db , TABLES.SESSION_INFO.TABLE_NAME , TABLES.SESSION_INFO.TABLE_ID_COLUMN);

  userContactMapper = new BaseMapper(db , TABLES.USER_CONTACT.TABLE_NAME , TABLES.USER_CONTACT.TABLE_ID_COLUMN);

  /**
   * 保存消息
   * @param data
   */
  async saveMessage(data) {
    console.log('开始保存消息：' , data)
    // 先看下消息所在会话是否存在 不存在先创建
    const {contactId} = data
    console.log('解析的contactId：' , contactId)

    // todo 保存或修改会话列表
    const sessionList = await this.sessionListMapper.list({createUser : userStore.uid , sessionId : data.sessionId})
    console.log('列表:' , sessionList)

    if (!sessionList || sessionList.list.length === 0) {

      // 全局加锁
      await Lock.runExclusive(async () => {
        console.log('会话不存在，新增')
        const contact = await this.userContactMapper.getOne({contactId : contactId})
        console.log('查到的联系人:' , contact)
        const sessionListEntity = {
          contactId : contactId,
          sessionId: data.sessionId,
          contactName: contact.contactRemark,
          lastMessage : data.content,
          lastTime: data.createTime,
          lastAvatar: contact.avatar,
          isShow: 1,
          isOwner: session.isOwner === 1? 1 : 2,
          createTime: data.createTime,
          createUser : userStore.uid,
          updateTime : data.createTime,
          updateUser: userStore.uid

        }
        console.log('插入会话：' , sessionListEntity)
        await this.sessionListMapper.save(sessionListEntity)


      });

    } else {

      // 更新最后一条消息
      const session = sessionList.list[0]
      const contact = await this.userContactMapper.getOne({contactId : session.contactId})
      console.log('会话存在，更新' , sessionList)
      session.lastTime = data.createTime
      session.lastMessage = data.content
      session.lastAvatar = contact.avatar
      if (contact.contactRemark) {
        session.contactName = contact.contactRemark
      } else {
        session.contactName = contact.nickName
      }
      session.updateTime = data.createTime
      session.updateUser = data.createUser
      if (data.type === 1) {
        session.isOwner = 1
      } else {
        session.isOwner = 2
      }
       await this.sessionListMapper.updateById(session)
    }

    delete data.contactId
    if (!data.messageId) {
      data.messageId = generateUUID()
      const result = await this.chatListMapper.save(data)
    } else {

      // 存在messageId检查下是否已经存入
      const message = await this.chatListMapper.getOne({messageId : data.messageId , createUser : userStore.uid})
      if (!message) {
        console.log('消息不存在新增')
        await this.chatListMapper.save(data)
      } else {
        console.log('消息已存在，不新增' , userStore.uid)
      }
    }
    return data.messageId

  }

}

export default MessageService
